/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 *
 *SdProjectPlanController
 * SD项目策划
 *
 * 修改纪录
 * 2021-12-16 版本：1.0 hudeyong 创建。
 * @version 版本：1.0
 * @author 作者：hudeyong
 * 创建日期：2021-12-16
 */

package com.topscomm.gpm.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.topscomm.gpm.controller.auto.GpmProjectPlanControllerAuto;
import com.topscomm.pub.util.*;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.topscomm.gpm.pojo.GpmProjectEntity;
import com.topscomm.gpm.pojo.GpmProjectMilepostEntity;
import com.topscomm.gpm.pojo.GpmProjectPlanEntity;
import com.topscomm.gpm.service.impl.GpmProjectMilepostService;
import com.topscomm.gpm.service.impl.GpmProjectService;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.service.impl.CboApprovalNodeInsService;
import com.topscomm.pub.vo.ResponseResult;

/**
 * @author: hudeyong
 * @date: 2021-12-16
 * @description:SD项目策划Controller
 * @modify:
 */
@RestController
@RequestMapping("sd/projectPlan")
public class GpmProjectPlanController extends GpmProjectPlanControllerAuto implements IGpmProjectPlanController {
    @Autowired
    private GpmProjectMilepostService gpmProjectMilepostService;
    @Autowired
    private GpmProjectService gpmProjectService;
    @Autowired
    private CboApprovalNodeInsService cboApprovalNodeInsService;

	/**
	 * @author: hudeyong
	 * @date: 2021-12-16
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		  this.getUserBean();
	        StringBufferProxy sql = new StringBufferProxy();
	        sql.appendSingle(" 1=1 ");
	        if (paraMap.containsKey("qry_proposalname")) {
	            String value = paraMap.get("qry_proposalname").toString();
	            if (!StringUtil.isEmpty(value)) {
	                sql.appendSingle(" and proposalname like '%{0}%' ", value);
	            }
	        }
	        if (paraMap.containsKey("qry_planner")) {
	            String value = paraMap.get("qry_planner").toString();
	            if (!StringUtil.isEmpty(value)) {
	                sql.appendSingle(" and planner like '%{0}%' ", value);
	            }
	        }

	        if (paraMap.containsKey("qry_projectname")) {
	            String value = paraMap.get("qry_projectname").toString();
	            if (!StringUtil.isEmpty(value)) {
	                sql.appendSingle(" and projectname like '%{0}%' ", value);
	            }
	        }
			if (paraMap.containsKey("qry_projectnameforfile")) {
				String value = paraMap.get("qry_projectnameforfile").toString();
				if (!StringUtil.isEmpty(value)) {
					sql.appendSingle(" and GpmProjectPlan.projectname like '%{0}%' ", value);
				}
			}
	        if (paraMap.containsKey("qry_projectcode")) {
	            String value = paraMap.get("qry_projectcode").toString();
	            if (!StringUtil.isEmpty(value)) {
	                sql.appendSingle(" and projectcode  = '{0}' ", value);
	            }
	        }

	        if (paraMap.containsKey("qry_begindocdate")) {
	            String value = paraMap.get("qry_begindocdate").toString();
	            if (!StringUtil.isEmpty(value)) {
	                sql.appendSingle(" and docdate >= {0} ",
	                    SQLAdapter.toDateLong(value + " 00:00:00"));
	            }
	        }
	        if (paraMap.containsKey("qry_enddocdate")) {
	            String value = paraMap.get("qry_enddocdate").toString();
	            if (!StringUtil.isEmpty(value)) {
	                sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
	            }
	        }
	        if (paraMap.containsKey("qry_deptname")) {
	            String value = paraMap.get("qry_deptname").toString();
	            if (!StringUtil.isEmpty(value)) {
	                sql.appendSingle(
	                    " and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))",
	                    value);
	            }
	        }
	        if (paraMap.containsKey("qry_state")) {
	            String value = paraMap.get("qry_state").toString();
	            if (!StringUtil.isEmpty(value)) {
	                sql.appendSingle(" and state in ({0})", value);
	            }
	        }
	        if (paraMap.containsKey("qry_enabled")) {
	            String value = paraMap.get("qry_enabled").toString();
	            if (!StringUtil.isEmpty(value)) {
	                sql.appendSingle(" and enabled = {0} ", value);
	            }
	        }
	        if (paraMap.containsKey("qry_where")) {
	            String value = paraMap.get("qry_where").toString();
	            if (!StringUtil.isEmpty(value)) {
	                sql.appendSingle(" and {0}", value);
	            }
	        }
	        if (paraMap.containsKey("qry_proposalcode")) {
	        	String value = paraMap.get("qry_proposalcode").toString();
	        	if (!StringUtil.isEmpty(value)) {
	        		sql.appendSingle(" and proposalcode like '%{0}%'", value);
				}
			}
	        return sql.toString();
	}

	/**
	 * @author: hudeyong
	 * @date: 2021-12-16
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

    /**
    *
    * @description: 提交审批前
    * @param dataMap
    * @param paraMap
    * @throws Exception
    * @author: wudaliang
    * @date: 2021-01-07
    * @modify:
    */
   @Override
   protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
       super.beforeSubmit(dataMap, paraMap);
       StringBufferProxy mailtitle = new StringBufferProxy();
       mailtitle.appendSingle("{0}{1}于{2}提交项目策划申请,单据编号{3}! ",
       		dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
       dataMap.put("maintitle", mailtitle.toString());
   }

   @PutMapping({"/approval"})
   @Override
   public ResponseResult<Object> approval(@RequestBody(required = false) Map<String, Object> paraMap) {
       try {
           String approvalOpinion = paraMap.get("approvalopinion").toString();
           String approvalType = paraMap.get("approvaltype").toString();
           String nodeInsId = paraMap.get("nodeinsid").toString();
           String backNodeId = ConvertUtil.convertToString(paraMap.get("backnodeid"));
           long nextUserId = 0L;
           if (paraMap.containsKey("nextuserid") && !StringUtil.isEmpty(paraMap.get("nextuserid").toString())) {
               nextUserId = Long.parseLong(paraMap.get("nextuserid").toString());
           }
           if("".equals(approvalOpinion)&&"1".equals(approvalType)){
               approvalOpinion="同意";
           }
           this.service.executeApprove(nodeInsId, new Date(), approvalOpinion, approvalType, backNodeId, this.getUserBean(), nextUserId);
           return ResponseResult.ok("操作成功");
       } catch (Exception var8) {
           return this.handleControllerException(var8);
       }
   }

   /**
     * @author: hdy
     * @date: 2021-12-18
    * @param: dataMap
    * @param: paraMap
    * @description: 加载项目信息
    * @return: void
    * @modify:
    */
	@GetMapping(value = "/projectLoadInfo")
	public ResponseResult<Object> milepostLoadInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
		String projectCode = ConvertUtil.convertToString(paraMap.get("projectCode"));
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("projectCode = '{0}'",projectCode);
		List<GpmProjectEntity> sdProjectEntities = gpmProjectService.queryByWhere(sql.toString());
		if(sdProjectEntities.size()==0) {
			throw new ServiceException("没有找到通用项目信息");
		}
		paraMap.put("projectinfo", sdProjectEntities.get(0));
		return ResponseResult.ok(paraMap);
   }

    /**
     * @author: hdy
     * @date: 2021-12-18
     * @description: 判断是否是第一次策划
     * @modify:
     */
	@GetMapping(value = "/checkplancount")
	public ResponseResult<Object> checkplancount(@RequestParam(required = false) Map<String, Object> paraMap) {
        String projectcode = ConvertUtil.convertToString(paraMap.get("projectcode"));
        Boolean isadd = ConvertUtil.convertToBoolean(paraMap.get("isadd"));
        StringBufferProxy whereSql = new StringBufferProxy();
        if (isadd) {
            whereSql.appendSingle(" projectcode = '{0}' and state = '9' ", projectcode);
        } else {
            String id = ConvertUtil.convertToString(paraMap.get("id"));
            whereSql.appendSingle(" id = {1} and projectcode = '{0}' and version != '1' ",
                    projectcode, id);
        }
        paraMap.put("isFirstPlan", this.service.getCount(whereSql.toString()) <= 0);
        return ResponseResult.ok(paraMap);
    }

    /**
     * @author: hdy
     * @date: 2021-12-18
     * @description: 查询当前用户可查看的与公开的记录，且项目已结项
     * @modify:
     */
    @GetMapping(value = "/loadPlanInfo")
    public ResponseResult<Object> loadPlanInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
        	String milepostcode = ConvertUtil.convertToString(paraMap.get("milepostcode"));
        	StringBufferProxy sql = new StringBufferProxy();
        	sql.appendSingle("id = (select max(planid) from {0} where operatecode = '{1}' and enabled = 1 )", GpmProjectMilepostEntity.tableName, milepostcode);
        	List<GpmProjectPlanEntity> sdProjectPlanEntities = this.service.queryByWhere(sql.toString());
        	boolean key = sdProjectPlanEntities.size() <= 0 || sdProjectPlanEntities.get(0).getState() != 9;
			return ResponseResult.ok(key);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

	/**
	 * @author: zhangjunayo
	 * @date: 2021-12-22
	 * @description: 项目归档list方法
	 * @modify:
	 */
	@GetMapping(value = "/listForOpen")
	public ResponseResult<Object> listForOpen(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sql = this.spellListSql(paraMap);
			Map<String, Object> sqlMap = new HashMap<>();
			sqlMap.put("whereSql", sql);
			int totalCount = this.service.getCount(sqlMap, "getCountForFile");
			List<Map<String, Object>> tempList = null;
			if (query.getPageSize() > 0) {
				tempList = this.service.queryMapForPage(sqlMap, "queryMapForFile");
			} else {
				tempList = this.service.queryMapByWhere(sql, "queryMapForFile");
			}
			this.service.setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
}

